(ns ura.data.OrgInfo
  (:require
   [taoensso.telemere :as t]
   [cheshire.core :as json]
   [next.jdbc :as jdbc]
   [ura.config :as cfg]
   [ura.data.Data :refer [executeSql checkDataNull upcaseKey]]
   )
  (:use tupelo.core)
  )


(defn queryOrgById [id]
  (executeSql {:select [:*]
                  :from :ORG_INFO
                  :where [:= :ID id]})
  )


(defn queryOrgByName [name]
  (executeSql {:select [:*]
                  :from :ORG_INFO
                  :where [:= :NAME name]})
  )


(defn queryOrgInfo "查询组织信息"
  [params]
  (t/log!  ["query org by: " params])
  (let [name (:name params)
        code (:code params)
        state (:state params)
        parent_id (:parent_id params)
        data (executeSql {:select [:*]
                             :from [:ORG_INFO]
                             :where [:and
                                     (when (checkDataNull name) [:like :NAME (str "%" name "%")])
                                     (when (checkDataNull code) [:like :CODE (str "%" code "%")])
                                     (when (checkDataNull state)  [:= :STATE state])
                                     (when (checkDataNull parent_id) [:= :PARENT_ID parent_id])
                                     ]
                             })
        data1 (doall (map (fn [o] (assoc o :infos (json/decode (:infos o))))  data))
        ]
    (spy data1)
    data1
    )
  )


(defn updateOrg [orgData]
  (t/log!  ["update org rquest: " orgData])
  (let [id (:id orgData)
        org (merge (upcaseKey (select-keys orgData [:name :code :description :state :parent_id]))
                   {:INFOS (json/encode (:infos orgData))}
                   )
        ]
    (executeSql {:update :ORG_INFO
                    :set org
                    :where [:= :id id]})
    )
  )


(defn insertOrg [orgData]
  (let [orgInfo (merge
                 (upcaseKey (select-keys orgData [:name :code :description :state :parent_id]))
                 {:INFOS (json/encode (:infos orgData))}
                 {:ID :ORG_INFO_SEQ.nextval}
                 )
        ]
    (executeSql {:insert-into [:ORG_INFO]
                    :values [orgInfo]
                    })
    )
  )


(defn saveOrg [orgData]
  (t/log!  ["get saveOrg request: " orgData])
  (let [isExist (first (queryOrgById (:id orgData)))]
    (if isExist
      (updateOrg orgData)
      (insertOrg orgData)
      )
    )
  )


(defn deleteOrg [id]
  (t/log!  ["delete org data: " id])
  (executeSql {:delete-from [:ORG_INFO]
                  :where [:= :ID id]
                  })
  )
